package com.easpeed.comon.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import com.blankj.utilcode.util.NetworkUtils


class SignalStrengthListener(val context: Context) : PhoneStateListener() {

    @SuppressLint("MissingPermission")
    override fun onSignalStrengthsChanged(signalStrength: SignalStrength) {
        super.onSignalStrengthsChanged(signalStrength)
        // 获取信号强度
        val signalInfo = signalStrength.toString()
//        signalStrength.gsmSignalStrength
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            val method = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                signalStrength.getCellSignalStrengths().get(0).level
            } else {
                TODO("VERSION.SDK_INT < Q")
            }

            com.bigyu.utils.Logger.e("TAG", "onSignalStrengthsChanged:${ NetworkUtils.getNetworkType()} ${   method}" )
        }


    }

  lateinit  var telephonyManager: TelephonyManager

    fun start() {
        if (!::telephonyManager.isInitialized) {
            telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        }
//
//        Logger.e("TAG", "获取当前信号强度等级")
        telephonyManager?.listen(this, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)

//
//        // position:0～5数值 0:无手机卡或者无信号强度 1～5 手机信号轻度，依次增大
//        PhoneStateUtils.registerPhoneStateListener(this, object : MyPhoneStateListenerListener {
//            fun onSignalStrengthsChanged(position: Int) {
//                Logger.e(TAG, "获取到onSignalStrengthsChanged: $position")
//            }
//        })
//
//
////获取当前信号强度
//        val currentSignalStrength: Int = PhoneStateUtils.getCurrentSignalStrength()
//        Logger.e(TAG, "currentSignalStrength: $currentSignalStrength")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                com.bigyu.utils.Logger.e("TAG", "onSignalStrengthsChanged22:${ NetworkUtils.getNetworkType()} ${telephonyManager?.signalStrength?.getCellSignalStrengths()}" )
            }

        }
    }

    fun stop() {
        telephonyManager?.listen(this, PhoneStateListener.LISTEN_NONE)
    }
}

